package com.atues.backtrack.combainationSum3;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    List<List<Integer>> res = new ArrayList<List<Integer>>();
    List<Integer> path = new ArrayList<Integer>();

    public List<List<Integer>> combinationSum3(int k, int n) {

        backtracking(n,k,0,1);
        return res;

    }

    void backtracking(int sum , int k,int currentSum,int start){
        if(path.size() == k && currentSum == sum){
            res.add(new ArrayList<>(path));
            return;
        }

        for(int i = start ; i <= 9 ; i++){
            if(currentSum + i > sum){//后面的值都会大于sum，所有该分支直接结束
                break;
            }
            path.add(i);
            currentSum += i;
            backtracking(sum,k,currentSum,i+1);
            currentSum -= i;
            path.remove(path.size() - 1);
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        List<List<Integer>> lists = solution.combinationSum3(3, 7);
        System.out.println(JSON.toJSONString(lists));
    }
}
